<template>
  <div class="post-management-container">
    <!-- 查询区域 -->
    <div class="search-area">
      <el-form
        :inline="true"
        :model="searchQuery"
        class="search-form"
      >
        <el-form-item label="帖子ID">
          <el-input
            v-model="searchQuery.post_id"
            placeholder="请输入帖子ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="发帖人ID">
          <el-input
            v-model="searchQuery.account_id"
            placeholder="请输入发帖人ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="板块">
          <el-select
            v-model="searchQuery.plate_id"
            placeholder="请选择板块"
            clearable
          >
            <el-option
              v-for="plate in plateList"
              :key="plate.plate_id"
              :label="plate.plate_name"
              :value="plate.plate_id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="审核状态">
          <el-select
            v-model="searchQuery.is_audited"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              label="待审核"
              :value="0"
            />
            <el-option
              label="已通过"
              :value="1"
            />
            <el-option
              label="已拒绝"
              :value="2"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button @click="handleReset">
            重置
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedPosts.length === 0"
            @click="batchDelete"
          >
            批量删除({{ selectedPosts.length }})
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 帖子管理表格 - 完全保留原有数据结构 -->
    <div class="table-area">
      <el-table
        v-loading="loading"
        :data="currentPageData"
        border
        style="width: 100%; margin-top: 20px"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontWeight: 'bold'
        }"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选列 -->
        <el-table-column
          type="selection"
          width="55"
          align="center"
        />

        <!-- 帖子ID列 -->
        <el-table-column
          prop="post_id"
          label="帖子ID"
          width="100"
          align="center"
        />

        <!-- 发帖用户列 -->
        <el-table-column
          label="发帖用户"
          width="180"
          align="center"
        >
          <template #default="{row}">
            <div class="user-info">
              <el-avatar
                :size="40"
                :src="row.avatar || defaultAvatar"
              />
              <div class="user-meta">
                <div class="username">
                  {{ row.nickname }}
                </div>

                <div class="user-id">
                  用户ID: {{ row.account_id }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 所属板块列 -->
        <el-table-column
          prop="plate_name"
          label="所属板块"
          width="120"
          align="center"
        />

        <!-- 标题列 -->
        <el-table-column
          prop="title"
          label="标题"
          width="180"
          align="center"
        />

        <!-- 内容预览列 -->
        <el-table-column
          label="内容预览"
          min-width="200"
          align="center"
        >
          <template #default="{row}">
            <div class="content-preview">
              <!-- 文字内容 -->
              <div class="text-content">
                {{ stripHtml(row.content).substring(0, 30) }}{{ row.content.length > 30 ? '...' : '' }}
              </div>

              <!-- 图片预览 -->
              <el-image
                v-if="hasValidImage(row)"
                :src="getFirstValidImage(row.media).url"
                :preview-src-list="getAllValidImages(row.media)"
                fit="contain"
                style="max-height: 60px;"
              >
                <div
                  slot="error"
                  class="image-error"
                >
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>

              <!-- 视频预览 -->
              <div
                v-if="hasValidVideo(row)"
                class="video-preview-container"
                @click.stop="showVideoPreview(getFirstValidVideo(row.media).url)"
              >
                <img
                  :src="getVideoPoster(getFirstValidVideo(row.media).url)"
                  style="object-fit: cover;"
                >
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 文件列 -->
        <el-table-column
          label="文件"
          width="120"
          align="center"
        >
          <template #default="{row}">
            <!-- 有有效媒体文件时 -->
            <div v-if="hasValidMedia(row)">
              <el-tag
                v-for="item in getValidMedia(row.media)"
                :key="item.media_id"
                :type="item.media_type === 2 ? 'info' : ''"
                size="small"
              >
                {{ item.media_type === 1 ? '图片' : '视频' }}
              </el-tag>
            </div>

            <!-- 无有效媒体文件但有文字内容时 -->
            <el-tag
              v-else-if="row.content"
              type="success"
              size="small"
            >
              文字
            </el-tag>

            <!-- 完全无内容时 -->
            <span v-else>无</span>
          </template>
        </el-table-column>

        <!-- 评论数列 -->
        <el-table-column
          prop="comment_count"
          label="评论数"
          width="80"
          align="center"
        />

        <!-- 点赞数列 -->
        <el-table-column
          prop="like_count"
          label="点赞数"
          width="80"
          align="center"
        />

        <!-- 审核状态列 -->
        <el-table-column
          label="审核状态"
          width="120"
          align="center"
        >
          <template #default="{row}">
            <el-tag :type="row.is_audited === 1 ? 'success' : row.is_audited === 2 ? 'danger' : 'warning'">
              {{ row.is_audited === 1 ? '已通过' : row.is_audited === 2 ? '已拒绝' : '待审核' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 发帖地址列 -->
        <el-table-column
          prop="location_name"
          label="发帖地址"
          width="150"
          align="center"
        />

        <!-- 发帖时间列 -->
        <el-table-column
          prop="create_time"
          label="发帖时间"
          width="180"
          align="center"
        />

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          width="220"
          align="center"
        >
          <template #default="{row}">
            <el-button
              size="mini"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              @click="showDetail(row)"
            >
              详情
            </el-button>
            <el-button
              v-if="row.is_audited !== 1"
              size="mini"
              type="success"
              @click="handleAudit(row.post_id, 1)"
            >
              通过
            </el-button>
            <el-button
              v-if="row.is_audited !== 2"
              size="mini"
              type="warning"
              @click="handleAudit(row.post_id, 2)"
            >
              拒绝
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(row.post_id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="custom-pagination">
      <div class="pagination-content">
        <span class="total-info">共 {{ pagination.total }} 条记录</span>

        <el-pagination
          ref="pagination"
          :current-page.sync="pagination.currentPage"
          :page-size.sync="pagination.pageSize"
          :total="pagination.total"
          :pager-count="5"
          :page-sizes="[6, 12, 18]"
          layout="prev, pager, next, sizes"
          @current-change="handleCurrentChange"
          @size-change="handlePageSizeChange"
        />

        <div class="page-jump">
          <span>前往</span>
          <el-input
            v-model.number="jumpPage"
            size="mini"
            style="width: 60px"
            @keyup.enter.native="handleJumpPage"
          />
          <span>页</span>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑帖子"
      :visible.sync="editDialogVisible"
      width="50%"
      :modal="false"
    >
      <el-form
        :model="editForm"
        label-width="80px"
      >
        <el-form-item label="帖子标题">
          <el-input
            v-model="editForm.title"
            placeholder="请输入帖子标题"
          />
        </el-form-item>

        <el-form-item label="所属板块">
          <el-select
            v-model="editForm.plate_id"
            placeholder="请选择板块"
          >
            <el-option
              v-for="plate in plateList"
              :key="plate.plate_id"
              :label="plate.plate_name"
              :value="plate.plate_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="帖子内容">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入帖子内容"
          />
        </el-form-item>

        <el-form-item label="审核状态">
          <el-select
            v-model="editForm.is_audited"
            placeholder="请选择状态"
          >
            <el-option
              label="待审核"
              :value="0"
            />
            <el-option
              label="已通过"
              :value="1"
            />
            <el-option
              label="已拒绝"
              :value="2"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="附件">
          <div
            v-if="editForm.media && editForm.media.length"
            class="media-container"
          >
            <div class="media-list">
              <div
                v-for="(item, index) in editForm.media"
                :key="index"
                class="media-item"
              >
                <el-image
                  v-if="item.media_type === 1"
                  style="width: 100px; height: 100px;"
                  :src="item.url"
                  :preview-src-list="getAllImages(editForm.media)"
                  fit="cover"
                />
                <div
                  v-else
                  class="video-item"
                >
                  <img
                    :src="getVideoPoster(item.url)"
                    class="video-thumbnail"
                    @error="handleImageError"
                  >
                  <div class="video-play-icon">
                    <i class="el-icon-video-play" />
                  </div>
                </div>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  style="position: absolute; right: 5px; top: 5px;"
                  @click="removeMedia(index)"
                />
              </div>
            </div>
          </div>
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleMediaChange"
          >
            <el-button size="small">
              上传附件
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="editDialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="saveEdit"
        >
          保存
        </el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="帖子详情"
      :visible.sync="detailVisible"
      width="70%"
      top="5vh"
      :close-on-click-modal="false"
      :modal="false"
    >
      <div
        v-if="currentDetail"
        class="detail-content"
      >
        <el-row :gutter="20">
          <el-col :span="16">
            <div class="post-content">
              <h3>{{ currentDetail.title }}</h3>
              <div class="user-info">
                <el-avatar
                  :size="50"
                  :src="currentDetail.avatar || defaultAvatar"
                />
                <div class="user-meta">
                  <div class="user-id">
                    用户ID: {{ currentDetail.account_id }}
                  </div>
                  <div class="post-time">
                    {{ currentDetail.create_time }}
                  </div>
                </div>
              </div>
              <div class="content-box">
                <pre style="white-space: pre-wrap;">{{ stripHtml(currentDetail.content) }}</pre>
              </div>
              <div
                v-if="currentDetail.media && currentDetail.media.length"
                class="media-container"
              >
                <h4>附件：</h4>
                <div class="media-list">
                  <div
                    v-for="item in currentDetail.media"
                    :key="item.media_id"
                    class="media-item"
                  >
                    <el-image
                      v-if="item.media_type === 1"
                      style="width: 200px; height: 150px;"
                      :src="item.url"
                      :preview-src-list="getAllImages(currentDetail.media)"
                      fit="cover"
                    />
                    <div
                      v-else
                      class="video-item"
                    >
                      <video
                        controls
                        style="width: 200px; height: 150px;"
                        :poster="getVideoPoster(item.url)"
                      >
                        <source
                          :src="item.url"
                          type="video/mp4"
                        >
                      </video>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="post-meta">
              <el-descriptions
                :column="1"
                border
              >
                <el-descriptions-item label="帖子ID">
                  {{ currentDetail.post_id }}
                </el-descriptions-item>
                <el-descriptions-item label="所属板块">
                  {{ currentDetail.plate_name }}
                </el-descriptions-item>
                <el-descriptions-item label="审核状态">
                  <el-tag :type="getStatusTagType(currentDetail.is_audited)">
                    {{ getStatusText(currentDetail.is_audited) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="发帖地址">
                  {{ currentDetail.location_name || '无' }}
                </el-descriptions-item>
                <el-descriptions-item label="评论数">
                  {{ currentDetail.comment_count }}
                </el-descriptions-item>
                <el-descriptions-item label="点赞数">
                  {{ currentDetail.like_count }}
                </el-descriptions-item>
                <el-descriptions-item
                  v-if="currentDetail.is_audited === 2"
                  label="拒绝原因"
                >
                  {{ currentDetail.fail_reason || '无' }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 视频预览对话框 -->
    <el-dialog
      title="视频预览"
      :visible.sync="videoPreviewVisible"
      width="60%"
      top="5vh"
      :modal="false"
    >
      <video
        v-if="currentVideoUrl"
        controls
        autoplay
        style="width: 100%;"
        :src="currentVideoUrl"
      >
        您的浏览器不支持视频播放
      </video>
    </el-dialog>
  </div>
</template>

<script>

import $ from 'jquery'

export default {
  data () {
    return {
      loading: false, // 加载状态
      searchQuery: { // 搜索查询条件
        post_id: '', // 帖子ID
        account_id: '', // 发帖人ID
        plate_id: '', // 板块ID
        is_audited: '' // 审核状态
      },
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png', // 默认头像URL
      plateList: [ // 板块列表（从API获取）
        // { plate_id: 1, plate_name: '钓点分享' },
        // { plate_id: 2, plate_name: '装备测评' },
        // { plate_id: 3, plate_name: '技巧交流' },
        // { plate_id: 4, plate_name: '渔获展示' }
      ],
      allData: [ // 全部帖子数据（从API获取）
        // 示例数据保持不变
        // {
        //   post_id: 1,
        //   account_id: 101,
        //   avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        //   plate_id: 1,
        //   plate_name: '钓点分享',
        //   title: '周末钓鱼收获分享',
        //   content: '今天在XX水库钓到一条大鱼，重达5公斤！<br><img src="https://example.com/fish1.jpg">',
        //   is_audited: 1,
        //   fail_reason: '',
        //   comment_count: 15,
        //   like_count: 42,
        //   location_name: 'XX水库',
        //   create_time: '2023-05-01 10:00:00',
        //   media: [
        //     { media_id: 1, media_type: 1, url: 'https://example.com/fish1.jpg' }
        //   ]
        // },
      ],
      filteredData: [], // 筛选后的帖子数据
      currentPageData: [], // 当前页数据
      pagination: { // 分页配置
        currentPage: 1, // 当前页码
        pageSize: 6, // 每页条数
        total: 0 // 总条数，从后端获取
      },
      jumpPage: 1, // 页面跳转输入值
      editDialogVisible: false, // 编辑对话框显示状态
      editForm: { // 编辑表单数据
        post_id: '', // 帖子ID
        title: '', // 标题
        plate_id: '', // 板块ID
        content: '', // 内容
        is_audited: 0, // 审核状态
        media: [] // 媒体文件
      },
      detailVisible: false,
      currentDetail: null,
      selectedPosts: [],
      videoPreviewVisible: false,
      currentVideoUrl: ''
    }
  },
  computed: {
    // 直接使用this.currentPageData（从API获取的当前页数据）
    totalPages () {
      return Math.ceil(this.filteredData.length / this.pagination.pageSize)
    }
  },
  created () {
    this.fetchPostList()
  },
  methods: {

    /**
     * 获取板块列表（API调用）
     * 接口：GET /api/admin/plate/list
     */
    // fetchPlateList () {
    //   this.loading = true
    //   $.ajax({
    //     url: 'http://localhost:3000/api/getAllAuditPost',
    //     type: 'GET',
    //     dataType: 'json',
    //     success: (response) => {
    //       if (response.code === 200) {
    //         console.log(response.data)

    //         this.plateList = response.data
    //       } else {
    //         this.$message.error(response.message || '获取板块列表失败')
    //       }
    //     },
    //     error: (xhr, status, error) => {
    //       this.$message.error('请求板块列表失败: ' + error)
    //     },
    //     complete: () => {
    //       this.loading = false
    //     }
    //   })
    // },

    /**
     * 获取帖子列表（API调用）
     * 接口：GET /api/admin/post/list
     * 参数：this.searchQuery中的搜索条件
     */
    fetchPostList () {
      this.loading = true

      // 构造请求参数
      const params = {
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        ...this.searchQuery
      }

      // 清除空参数
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key]
        }
      })

      $.ajax({
        url: 'http://localhost:3000/api/getAllAuditPost',
        type: 'GET',
        dataType: 'json',
        data: params,
        success: (response) => {
          // 检查响应状态码
          if (response.code !== 200) {
            this.$message.error(response.message || '获取数据失败')
            return
          }

          // 确保响应数据结构正确
          if (!response.data || !Array.isArray(response.data.list)) {
            this.$message.error('返回数据格式异常')
            return
          }

          // 处理分页数据
          this.pagination.total = response.data.total || 0

          // 转换数据格式
          this.currentPageData = response.data.list.map(item => {
            // 处理媒体文件数据
            const media = item.postMedia
              ? (Array.isArray(item.postMedia) ? item.postMedia : [item.postMedia])
                .filter(m => m && m.url && m.url.trim() !== '')
                .map(m => ({
                  media_id: m.mediaId || Date.now(),
                  media_type: m.mediaType || 1,
                  url: m.url
                }))
              : []

            return {
              post_id: item.postId,
              account_id: item.accountId,
              title: item.title || '无标题',
              content: item.content || '',
              is_audited: item.isAudited ?? 0,
              fail_reason: item.failReason || '',
              create_time: item.createTime || new Date().toLocaleString(),
              plate_id: item.plate?.plateId || 0,
              plate_name: item.plate?.plateName || '未知板块',
              avatar: item.user?.avatar || this.defaultAvatar,
              nickname: item.user?.nickname || '匿名用户',
              location_name: item.postLocation?.locationName || '',
              media,
              comment_count: item.commentCount || 0,
              like_count: item.likeCount || 0
            }
          })

          // 强制更新分页组件状态
          this.$nextTick(() => {
            if (this.$refs.pagination) {
              this.$refs.pagination.internalCurrentPage = this.pagination.currentPage
              this.$refs.pagination.lastEmittedPage = this.pagination.currentPage
            }
          })

          // 如果当前页无数据且不是第一页，则自动返回第一页
          if (this.currentPageData.length === 0 && this.pagination.currentPage > 1) {
            this.pagination.currentPage = 1
            this.jumpPage = 1
            this.fetchPostList()
          }
        },
        error: (xhr) => {
          this.$message.error(`数据加载失败: ${xhr.statusText}`)
          console.error('API请求失败:', xhr)

          // 出错时重置状态
          this.pagination.currentPage = 1
          this.jumpPage = 1
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    // 辅助方法
    // 检查是否有有效的图片
    hasValidImage (row) {
      return row.media && row.media.some(m => m.media_type === 1 && m.url && m.url.trim() !== '')
    },
    // 检查是否有有效的视频
    hasValidVideo (row) {
      return row.media && row.media.some(m => m.media_type === 2 && m.url && m.url.trim() !== '')
    },
    // 获取第一个有效的图片
    getFirstValidImage (media) {
      return media && media.find(m => m.media_type === 1 && m.url && m.url.trim() !== '')
    },
    // 获取第一个有效的视频
    getFirstValidVideo (media) {
      return media && media.find(m => m.media_type === 2 && m.url && m.url.trim() !== '')
    },
    // 获取所有有效的图片 URL
    getAllValidImages (media) {
      return media
        ? media.filter(m => m.media_type === 1 && m.url && m.url.trim() !== '').map(m => m.url)
        : []
    },
    // 获取所有有效的图片URL（修复方法未定义错误）
    getAllImages (media) {
      if (!media) return []
      return media
        .filter(m => m.media_type === 1 && m.url?.trim()) // 过滤图片类型且URL非空
        .map(m => m.url)
    },
    // 检查是否有有效的媒体文件
    hasValidMedia (row) {
      return row.media && row.media.some(m => m.url && m.url.trim() !== '')
    },
    // 获取所有有效的媒体文件
    getValidMedia (media) {
      return media ? media.filter(m => m.url && m.url.trim() !== '') : []
    },

    // 获取媒体类型标签样式
    getMediaTagType (type) {
      const typeMap = {
        1: '', // 图片 - 默认样式
        2: 'info', // 视频 - 信息样式
        3: 'success' // 文字 - 成功样式
      }
      return typeMap[type] || ''
    },

    // 获取媒体类型文本
    getMediaTypeText (type) {
      const typeMap = {
        1: '图片',
        2: '视频',
        3: '文字'
      }
      return typeMap[type] || '未知'
    },

    // 核心方法
    stripHtml (html) {
      if (!html) return ''
      return html.replace(/<br\s*\/?>/gi, '\n')
        .replace(/<[^>]*>/g, '')
        .trim()
    },

    getVideoPoster (videoUrl) {
      // 如果有真实封面图逻辑
      // return videoUrl.replace('.mp4', '_cover.jpg');

      // 使用带播放图标的SVG封面
      return ''
    },

    showVideoPreview (videoUrl) {
      this.currentVideoUrl = videoUrl
      this.videoPreviewVisible = true
    },

    handleImageError (e) {
      e.target.src = this.getVideoPoster()
    },

    getStatusText (status) {
      const statusMap = { 0: '待审核', 1: '已通过', 2: '已拒绝' }
      return statusMap[status] || '未知'
    },
    getStatusTagType (status) {
      const typeMap = { 0: 'warning', 1: 'success', 2: 'danger' }
      return typeMap[status] || ''
    },
    handleSearch () {
      // this.loading = true
      this.pagination.currentPage = 1
      this.fetchPostList() // 直接重新获取数据
    },

    handleReset () {
      this.searchQuery = {
        post_id: '',
        account_id: '',
        plate_id: '',
        is_audited: ''
      }
      this.pagination.currentPage = 1
      this.pagination.pageSize = 6 // 重置为默认值
      this.jumpPage = 1
      this.fetchPostList() // 重新加载数据
    },

    // 文件上传处理
    handleMediaChange (file) {
      const isImage = file.raw.type.includes('image/')
      const isVideo = file.raw.type.includes('video/')

      if (!isImage && !isVideo) {
        this.$message.error('只能上传图片或视频文件')
        return false
      }

      if (file.size / 1024 / 1024 > 20) {
        this.$message.error('文件大小不能超过20MB')
        return false
      }

      const newMedia = {
        media_id: Date.now(),
        media_type: isImage ? 1 : 2,
        url: URL.createObjectURL(file.raw),
        file: file.raw
      }

      this.editForm.media.push(newMedia)
    },
    // 表格选择变化事件
    handleSelectionChange (selection) {
      this.selectedPosts = selection.map(item => item.post_id)
    },

    // 统一的分页处理方法
    handleCurrentChange (newPage) {
      this.pagination.currentPage = newPage
      this.jumpPage = newPage

      // 强制同步分页组件状态
      this.$nextTick(() => {
        if (this.$refs.pagination) {
          this.$refs.pagination.internalCurrentPage = newPage
        }
      })

      // 加载数据
      this.fetchPostList()
    },

    handlePageSizeChange (newSize) { // ✅ 正确：使用参数newSize
      this.pagination.pageSize = newSize
      this.pagination.currentPage = 1 // 重置到第一页
      this.jumpPage = 1

      // 强制同步分页组件状态
      this.$nextTick(() => {
        if (this.$refs.pagination) {
          this.$refs.pagination.internalCurrentPage = 1
        }
      })

      this.fetchPostList()
    },

    // 每页条数变化
    handleSizeChange (newSize) {
      this.pagination.pageSize = newSize
      this.pagination.currentPage = 1 // 重置到第一页
      this.jumpPage = 1
      this.fetchPostList()
    },

    // 跳转页面方法
    handleJumpPage () {
      const pageNum = parseInt(this.jumpPage)
      const maxPage = Math.ceil(this.pagination.total / this.pagination.pageSize)

      if (pageNum >= 1 && pageNum <= maxPage) {
        this.handleCurrentChange(pageNum)
      } else {
        this.$message.warning(`请输入1-${maxPage}之间的页码`)
        this.jumpPage = this.pagination.currentPage
      }
    },

    // 帖子操作相关方法
    handleEdit (row) {
      this.editForm = {
        post_id: row.post_id,
        title: row.title,
        plate_id: row.plate_id,
        content: row.content,
        is_audited: row.is_audited,
        media: [...row.media]
      }
      this.editDialogVisible = true
    },

    // 修改saveEdit方法，添加API调用
    saveEdit () {
      if (!this.editForm.title) {
        this.$message.error('请输入标题')
        return
      }

      if (!this.editForm.content) {
        this.$message.error('请输入内容')
        return
      }

      this.loading = true

      // 构造表单数据
      const formData = new FormData()
      formData.append('post_id', this.editForm.post_id)
      formData.append('title', this.editForm.title)
      formData.append('plate_id', this.editForm.plate_id)
      formData.append('content', this.editForm.content)
      formData.append('is_audited', this.editForm.is_audited)

      // 添加媒体文件
      this.editForm.media.forEach((media, index) => {
        if (media.file) {
          formData.append(`media[${index}]`, media.file)
        }
      })

      // 提交编辑
      $.ajax({
        url: '/api/admin/post/update',
        type: 'POST',
        data: formData,
        processData: false, // 必须设置为false
        contentType: false, // 必须设置为false
        success: (response) => {
          if (response.code === 200) {
            this.$message.success('编辑成功')
            this.editDialogVisible = false
            this.fetchPostList() // 刷新列表
          } else {
            this.$message.error(response.message || '编辑失败')
          }
        },
        error: (xhr, status, error) => {
          this.$message.error('编辑请求失败: ' + error)
        },
        complete: () => {
          this.loading = false
        }
      })
    },

    removeMedia (index) {
      this.editForm.media.splice(index, 1)
    },

    showDetail (row) {
      this.currentDetail = row
      this.detailVisible = true
    },

    handleAudit (postId, status) {
      if (status === 2) {
        this.$prompt('请输入拒绝原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '拒绝原因不能为空'
        }).then(({ value }) => {
          this.updatePostStatus(postId, status, value)
        }).catch(() => {
          this.$message.info('已取消操作')
        })
      } else {
        this.updatePostStatus(postId, status)
      }
    },

    /**
     * 更新帖子状态（API调用）
     * 接口：POST /api/admin/post/audit
     * @param {Number} postId 帖子ID
     * @param {Number} status 审核状态
     * @param {String} [reason=''] 拒绝原因（可选）
     */
    updatePostStatus (postId, status, reason = '') {
      this.loading = true
      $.ajax({
        url: 'http://localhost:3000/api/auditPost',
        type: 'POST',
        dataType: 'json',
        data: {
          postId, // 改为 postId
          auditStatus: status, // 改为 auditStatus
          failReason: reason // 改为 failReason
        },
        success: (response) => {
          console.log(postId)
          if (response.code === 200) {
            this.$message.success('操作成功')
            this.fetchPostList() // 刷新列表
          } else {
            this.$message.error(response.message || '操作失败')
          }
        },
        error: (xhr, status, error) => {
          this.$message.error('操作请求失败: ' + error)
        },
        complete: () => {
          this.loading = false
        }
      })
    },

    /**
     * 删除单个帖子（API调用）
     * 接口：POST /api/admin/post/delete
     * @param {Number} postId 帖子ID
     */
    handleDelete (postId) {
      this.$confirm('确定删除该帖子吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        $.ajax({
          url: '/api/admin/post/delete',
          type: 'POST',
          dataType: 'json',
          data: { post_id: postId },
          success: (response) => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchPostList() // 刷新列表
            } else {
              this.$message.error(response.message || '删除失败')
            }
          },
          error: (xhr, status, error) => {
            this.$message.error('删除请求失败: ' + error)
          },
          complete: () => {
            this.loading = false
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    /**
     * 批量删除帖子（API调用）
     * 接口：POST /api/admin/post/batch-delete
     */
    batchDelete () {
      if (this.selectedPosts.length === 0) {
        this.$message.warning('请先选择要删除的帖子')
        return
      }

      this.$confirm(`确定删除选中的${this.selectedPosts.length}条帖子吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        $.ajax({
          url: '/api/admin/post/batch-delete',
          type: 'POST',
          dataType: 'json',
          data: { post_ids: this.selectedPosts },
          success: (response) => {
            if (response.code === 200) {
              this.$message.success('批量删除成功')
              this.selectedPosts = []
              this.fetchPostList() // 刷新列表
            } else {
              this.$message.error(response.message || '批量删除失败')
            }
          },
          error: (xhr, status, error) => {
            this.$message.error('批量删除请求失败: ' + error)
          },
          complete: () => {
            this.loading = false
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }

  }
}
</script>

<style scoped>
/* 基础容器样式 */
.post-management-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

/* 搜索区域样式 */
.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.user-info .user-id {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

/* 内容预览样式 */
.content-preview {
  font-size: 13px;
  line-height: 1.5;
  color: #606266;
  white-space: pre-wrap;
}

.content-preview .el-image {
  width: auto;
  max-width: 100%;
  height: 60px;
}

.content-preview .el-image img {
  object-fit: contain;
  height: 100%;
  width: auto;
  max-width: 120px;
}

.video-thumbnail {
  object-fit: contain;
  height: 100%;
  width: auto;
  max-width: 120px;
}

/* 视频预览样式 */
.video-preview-container {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 60px;
  margin-top: 5px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #eee;
}

.video-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background-color: #000;
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 24px;
  text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
}

video {
  background: #000 !important;
  outline: none !important;
}

/* 媒体相关样式 */
.media-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.media-container {
  margin-top: 10px;
}

.media-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.media-item {
  position: relative;
  border: 1px solid #eee;
  padding: 5px;
  border-radius: 4px;
}

.media-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}

.media-count {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 分页样式 - 重点优化区域 */
.custom-pagination {
  margin-top: 20px;
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: none;
  border: none;
}

.pagination-content {
  display: flex;
  align-items: center;
  gap: 15px;
  background: none;
  border: none;
}

.total-info {
  font-size: 13px;
  color: #606266;
}

.page-size-select {
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-size-select span {
  font-size: 13px;
  color: #606266;
}

.page-jump {
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-jump span {
  font-size: 13px;
  color: #606266;
}

/* 分页高亮样式 */
.custom-pagination >>> .el-pagination {
  padding: 0;
  background: transparent;
  border: none;
}

.custom-pagination >>> .el-pagination button {
  padding: 0 10px;
  height: 30px;
}

.custom-pagination >>> .el-pagination .el-pager li {
  min-width: 30px;
  height: 30px;
  line-height: 30px;
  margin: 0 2px;
  transition: all 0.3s;
}

.custom-pagination >>> .el-pager li.active {
  background-color: #409EFF !important;
  color: #fff !important;
  border-radius: 4px;
  font-weight: bold;
  cursor: default;
}

.custom-pagination >>> .el-pager li:hover {
  color: #409EFF !important;
}

.custom-pagination >>> .el-select {
  width: 70px;
}

/* 详情页样式 */
.detail-content {
  padding: 10px;
}

.post-content {
  padding-right: 20px;
}

.post-content h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 18px;
}

.post-content .user-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.post-content .user-meta {
  margin-left: 10px;
}

.post-content .user-id {
  font-size: 14px;
  font-weight: bold;
}

.post-content .post-time {
  font-size: 12px;
  color: #909399;
}

.content-box {
  line-height: 1.8;
  margin-bottom: 20px;
  white-space: pre-wrap;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .search-form .el-form-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }

  .custom-pagination {
    flex-wrap: wrap;
    justify-content: center;
  }

  .pagination-content {
    flex-wrap: wrap;
    justify-content: center;
    gap: 10px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .custom-pagination >>> .el-pager li.active {
    background-color: #66b1ff !important;
  }
}

/* 调整分页整体间距 */
.pagination-content {
  display: flex;
  align-items: center;
  gap: 20px; /* 增大各元素间距 */
}

/* 调整"前往"输入框样式 */
.page-jump {
  display: flex;
  align-items: center;
  margin-left: 35px; /* 与左侧元素间距 */
}

.jump-input {
  width: 60px;
  margin: 0 10px; /* 输入框左右间距 */
}

/* 调整"页"文字样式 */
.page-text {
  margin-left: 5px; /* 与输入框间距 */
}

/* 调整每页条数选择器样式 */
.el-pagination__sizes {
  margin: 0 15px !important; /* 增大与分页按钮的间距 */
}
</style>
